package com.jy.modules.cims.loan.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.CimsIrtUrlConstant;
import com.jy.modules.cims.common.JResult;
import com.jy.modules.cims.common.sysUtils.CollectionsUtils;
import com.jy.modules.cims.common.sysUtils.SearchParamUtil;
import com.jy.modules.cims.common.sysUtils.SimpleBeanUtils;
import com.jy.modules.cims.common.sysUtils.ViolationUtils;
import com.jy.modules.cims.component.common.service.TCMmTbjCreditMatchingService;
import com.jy.modules.cims.component.loan.TBJCLoanImpl;
import com.jy.modules.cims.data.common.dto.TCMmRaisePlanDTO;
import com.jy.modules.cims.data.common.dto.TCMmTbjCreditMatchingDTO;
import com.jy.modules.cims.data.common.dto.TCMmTbjLoanProdDTO;
import com.jy.modules.cims.data.dao.TbjLoanDao;
import com.jy.modules.cims.data.dto.inter.tbj.fk.LoanResultDto;
import com.jy.modules.cims.data.dto.inter.tbj.sd.CheckLoanDTO;
import com.jy.modules.cims.data.interact.tbj.loan.request.RequestAuditResultDTO;
import com.jy.modules.cims.data.interact.tbj.loan.request.RequestLoanResultDTO;
import com.jy.modules.cims.data.interact.tbj.loan.request.RequestProdInfoDTO;
import com.jy.modules.cims.data.interact.tbj.loan.request.RequestProdLoanDTO;
import com.jy.modules.cims.data.interact.tbj.loan.request.RequestRaisePlanDTO;
import com.jy.modules.cims.data.interact.tbj.loan.request.RequestTradeDebtorDTO;
import com.jy.modules.cims.data.interact.tbj.loan.response.ResponseDataDTO;
import com.jy.modules.cims.data.interact.tbj.loan.response.ResponseDataEnum;
import com.jy.platform.core.message.DataMsg;

/**
 * @description 铜板街贷款业务服务层。
 * @author shengzhoutao
 * @date 2015-09-07
 */
@Service("com.jy.modules.cims.loan.service.TBJLoanService")
public class TBJLoanService {
	private static final Logger logger = LoggerFactory.getLogger(TBJLoanService.class);

	@Autowired
	private TbjLoanDao tbjLoanDao;
	 
	@Autowired
	@Qualifier("com.jy.modules.cims.component.loan.TBJCLoanImpl")
	private TBJCLoanImpl tbjCLoanImpl;

	@Autowired
	@Qualifier("com.jy.modules.platform.tcmmtbjcreditmatching.service.TCMmTbjCreditMatchingService")
	private TCMmTbjCreditMatchingService tCMmTbjCreditMatchingService;

	/**
	 * @description 接收募集计划申请:接收铜板街提供我司的募集计划信息，在合作机构系统中进行募集计划信息登记，<br/>
	 *              并生成响应结果反馈给铜板街。
	 * @param parameter
	 *            接收参数对象
	 * @return ResponseDataDTO 响应结果
	 * @author shengzhoutao
	 * @throws Exception
	 * @date 2015-09-07
	 */
	public ResponseDataDTO doRaisePlan(final RequestRaisePlanDTO parameter) throws Exception {
		logger.info("接收募集计划申请==>>");

		String planId = parameter.getPlanId(); // 募集计划编号
		logger.info("募集计划编号:" + planId);

		// 根据募集计划编号查询 募集计划申请
		TCMmRaisePlanDTO histRaisePlan = tbjCLoanImpl.getRaisePlanByPlanId(planId);
		// 已经存在募集计划申请
		if (null != histRaisePlan) {
			// 已经入库
			return new ResponseDataDTO(planId, ResponseDataEnum.EXISTS);
		}

		// 不存在募集计划申请,登记募集计划申请.
		TCMmRaisePlanDTO newRaisePlan = new TCMmRaisePlanDTO();
		// 把parameter和newRaisePlan相同属性的value复制到newRaisePlan中
		SimpleBeanUtils.copyBean2Bean(newRaisePlan, parameter);

		// 登记募集计划申请
		long key = tbjCLoanImpl.registerRaisePlan(newRaisePlan);
		logger.info("登记募集计划申请生成的主键id:" + key);
		newRaisePlan = null;

		// 成功
		return new ResponseDataDTO(planId, ResponseDataEnum.SUCCESS);

	}

	/**
	 * @description 接收贷款审批结果:接收铜板街提供我司合作机构系统债务人审核结果，并在合作机构系统保存债务人审核结果信息，<br/>
	 *              同时生成响应结果反馈给铜板街 。
	 * @param parameter
	 *            接收参数对象
	 * @return ResponseDataDTO 响应结果
	 * @author shengzhoutao
	 * @throws Exception
	 * @date 2015-09-07
	 */
	public ResponseDataDTO doAuditResult(final RequestAuditResultDTO parameter) throws Exception {
		logger.info("接收贷款审批结果==>>");

		String streamId = parameter.getStreamId(); // 唯一标识本次审批结果
		String contractNo = parameter.getLoanNumber();// 借款信息审批编号

		logger.info("唯一标识本次审批结果编号:" + streamId);
		logger.info("借款信息审批编号:" + contractNo);

		String result = String.valueOf(parameter.getResult());
		ResponseDataDTO response = new ResponseDataDTO(parameter.getStreamId(), ResponseDataEnum.FAILURE);

		// 验证贷款审批
		JResult validateResult = tbjCLoanImpl.validateAuditResultByContractNo(contractNo);
		if (validateResult.isSuccess() == false) {
			if (validateResult.getErrCode().equals(String.valueOf(ResponseDataEnum.EXISTS.getCode()))) {
				return new ResponseDataDTO(parameter.getStreamId(), ResponseDataEnum.EXISTS);
			} else {
				response.setMessage(response.getMessage() + "[" + validateResult.getErrMsg() + "]");
				return response;
			}
		}

		// 审批通过
		if (CimsConstant.TBJ_AUDIT_RESULT_SUCCESS.equals(result)) {
			tbjCLoanImpl.auditLoan(contractNo, CimsConstant.LOAN_EACH_STATUS_AUDIT, CimsConstant.LOAN_CONFIRM_WIN,null);
			tbjCLoanImpl.approveConfrim(contractNo, CimsIrtUrlConstant.IRT_LOAN_APPROVE_SUCCESS);
		}
		// 审批失败
		else if (CimsConstant.TBJ_AUDIT_RESULT_FAIL.equals(result) || CimsConstant.TBJ_AUDIT_RESULT_RETURN.equals(result)) {
			tbjCLoanImpl.auditLoan(contractNo, CimsConstant.LOAN_EACH_STATUS_AUDIT, CimsConstant.LOAN_CONFIRM_LOSE,null);
			tbjCLoanImpl.approveConfrim(contractNo, CimsIrtUrlConstant.IRT_LOAN_APPROVE_FAIL);
		}
		// 审批中:目前不做处理
		else if (CimsConstant.TBJ_AUDIT_RESULT_ING.equals(result)) {
			logger.info("result:" + result + ", 审批中目前不做处理");
		}
		// 审批结果result值不正确
		else {
			response.setMessage(response.getMessage() + "[审批结果result值不正确,-3:通过 ,-2:退回,-1:未通过 ,0:审批中]");
			return response;
		}

		// 成功
		return new ResponseDataDTO(streamId, ResponseDataEnum.SUCCESS);
	}

	/**
	 * @description 接收贷款放款结果:接收铜板街提供我司合作机构系统放款结果，并在合作机构系统保存放款结果信息，<br/>
	 *              同时生成响应结果反馈给铜板街。
	 * @param parameter
	 *            接收参数对象
	 * @return ResponseDataDTO 响应结果
	 * @author shengzhoutao
	 * @throws Exception
	 * @date 2015-09-07
	 */
	public ResponseDataDTO doLoanResult(final RequestLoanResultDTO parameter) throws Exception {
		logger.info("接收贷款放款结果==>>");

		String streamId = parameter.getStreamId(); // 唯一标识本次审批结果
		String contractNo = parameter.getLoanNumber();// 借款信息审批编号

		logger.info("唯一标识本次审批结果编号:" + streamId);
		logger.info("借款信息审批编号:" + contractNo);

		String result = String.valueOf(parameter.getLoanResult());
		ResponseDataDTO response = new ResponseDataDTO(parameter.getStreamId(), ResponseDataEnum.FAILURE);

		// 验证贷款放款
		JResult validateResult = tbjCLoanImpl.validateLoanResultByContractNo(contractNo);
		if (validateResult.isSuccess() == false) {
			if (validateResult.getErrCode().equals(String.valueOf(ResponseDataEnum.EXISTS.getCode()))) {
				return new ResponseDataDTO(parameter.getStreamId(), ResponseDataEnum.EXISTS);
			} else {
				response.setMessage(response.getMessage() + "[" + validateResult.getErrMsg() + "]");
				return response;
			}
		}

		if (CimsConstant.TBJ_LOAN_RESULT_SUCCESS.equals(result) || CimsConstant.TBJ_LOAN_RESULT_FAIL.equals(result)) {
			List<LoanResultDto> loanResultDtoList = new ArrayList<LoanResultDto>();
			LoanResultDto loanResultDto = new LoanResultDto();
			loanResultDto.setLoanResult(parameter.getLoanResult());
			loanResultDto.setLoanNumber(contractNo);
			loanResultDto.setLoanTime(parameter.getLoanTime());
			loanResultDtoList.add(loanResultDto);
			// 贷款放款
			tbjCLoanImpl.updateLoanResult(loanResultDtoList);

			loanResultDto = null;
			loanResultDtoList = null;
		} else if (CimsConstant.TBJ_LOAN_RESULT_ING.equals(result)) {
			logger.info("result:" + result);
		} else {
			response.setMessage(response.getMessage() + "[放款结果result值不正确,-3:成功 ,1:失败, 0:放款中]");
			return response;
		}

		// 成功
		return new ResponseDataDTO(parameter.getStreamId(), ResponseDataEnum.SUCCESS);
	}

	/**
	 * @description 接收产品相关的债权信息:接收铜板街提供我司合作机构系统产品关联债权信息，并在合作机构系统保存产品关联债权信息，<br/>
	 *              同时生成响应结果反馈给铜板街 。
	 * @param parameter
	 *            接收参数对象
	 * @return ResponseDataDTO 响应结果
	 * @author shengzhoutao
	 * @throws Exception
	 * @date 2015-09-07
	 */
	public ResponseDataDTO doProdLoan(final RequestProdLoanDTO parameter) throws Exception {
		logger.info("接收产品相关的债权信息==>>");

		String productId = parameter.getProductId(); // 产品编号
		logger.info("产品编号:" + productId);

		TCMmTbjLoanProdDTO histLoanProd = tbjCLoanImpl.getLoanProdByProductId(productId);
		if (null != histLoanProd) {
			return new ResponseDataDTO(productId, ResponseDataEnum.EXISTS);
		}

		String[] loan = parameter.getLoan();
		if (null != loan && loan.length > 0) {
			TCMmTbjLoanProdDTO newLoanProd = new TCMmTbjLoanProdDTO();
			// 把parameter和newLoanProd相同属性的value复制到newLoanProd中
			SimpleBeanUtils.copyBean2Bean(newLoanProd, parameter);
			String loanNumbers = JSON.toJSONString(loan);
			newLoanProd.setLoanNumber(loanNumbers);
			long key = tbjCLoanImpl.registerTbjLoanProd(newLoanProd);
			logger.info("登记产品生成的主键id:" + key);

			for (String loanNumber : loan) {
				tbjCLoanImpl.updateLoanDetailProductCode(loanNumber, parameter.getProductId());
			}
			newLoanProd = null;
		} else {
			return new ResponseDataDTO(productId, ResponseDataEnum.FAILURE);
		}

		// 成功
		return new ResponseDataDTO(productId, ResponseDataEnum.SUCCESS);
	}
	/**
	 * @description 接收贷款相关的产品上架时间:接收铜板街提供我司合作机构系统产品上架时间，并在合作机构系统保存产品上架等信息，<br/>
	 *              同时生成响应结果反馈给铜板街 。
	 * @param parameter
	 *            接收参数对象
	 * @return ResponseDataDTO 响应结果
	 * @author zhangmi
	 * @throws Exception
	 * @date 2016-07-06
	 */
	public ResponseDataDTO doProdInfo(final RequestProdInfoDTO parameter) throws Exception {
		logger.info("接收铜板街贷款相关的上架信息==>>");

		String productId = parameter.getProductId(); // 产品编号
		logger.info("产品编号:" + productId);

		TCMmTbjLoanProdDTO histLoanProd = tbjCLoanImpl.getLoanProdByProductId(productId);
		if (null != histLoanProd) {
			return new ResponseDataDTO(productId, ResponseDataEnum.EXISTS);
		}
		String[] loan = parameter.getLoan();
		if (null != loan && loan.length > 0) {
			TCMmTbjLoanProdDTO newLoanProd = new TCMmTbjLoanProdDTO();
			// 把parameter和newLoanProd相同属性的value复制到newLoanProd中
			SimpleBeanUtils.copyBean2Bean(newLoanProd, parameter);
			String loanNumbers = JSON.toJSONString(loan);
			newLoanProd.setLoanNumber(loanNumbers);
			long key = tbjCLoanImpl.registerTbjProdInfo(newLoanProd);
			logger.info("铜板街贷款产品上架信息生成的主键id:" + key);
			newLoanProd = null;
		} else {
			return new ResponseDataDTO(productId, ResponseDataEnum.FAILURE);
		}

		// 成功
		return new ResponseDataDTO(productId, ResponseDataEnum.SUCCESS);
	}
	/**
	 * @description 接收铜板街提供我司合作机构系统债权匹配信息，并在合作机构系统保存债权匹配信息，同时生成响应结果反馈给铜板街。
	 * @param parameter
	 *            接收参数对象
	 * @return RequestTradeDebtorDTO 响应结果
	 * @author shengzhoutao
	 * @throws Exception
	 * @date 2015-09-07
	 */
	public ResponseDataDTO doTradeDebtor(final RequestTradeDebtorDTO parameter) throws Exception {
		logger.info("接收债权匹配信息==>>");
		String productId = parameter.getProductId(); // 产品编号
		logger.info("产品编号:" + productId);

		TCMmTbjCreditMatchingDTO tbjCreditMatchingDTO = new TCMmTbjCreditMatchingDTO();
		tbjCreditMatchingDTO.setProductId(productId);
		List<TCMmTbjCreditMatchingDTO> dataList = tCMmTbjCreditMatchingService.searchTCMmTbjCreditMatching(SearchParamUtil
				.getSearchParam(tbjCreditMatchingDTO));
		if (CollectionsUtils.isNotEmpty(dataList)) {
			return new ResponseDataDTO(productId, ResponseDataEnum.EXISTS);
		}

		String[] loan = parameter.getLoan();
		if (null != loan && loan.length > 0) {
			tbjCreditMatchingDTO.setFilePath(parameter.getFileUrl());
			tbjCreditMatchingDTO.setLoanIds(JSON.toJSONString(loan));
			tbjCreditMatchingDTO.setCreateTime(new Timestamp(System.currentTimeMillis()));
			tbjCreditMatchingDTO.setModifyTime(new Timestamp(System.currentTimeMillis()));
			tbjCreditMatchingDTO.setValidateState(CimsConstant.DATE_STATUS_VALID);
			tCMmTbjCreditMatchingService.insertTCMmTbjCreditMatching(tbjCreditMatchingDTO);

			tbjCreditMatchingDTO = null;
		} else {
			return new ResponseDataDTO(productId, ResponseDataEnum.FAILURE);
		}

		return new ResponseDataDTO(productId, ResponseDataEnum.SUCCESS);
	}

	/**
	 * @description 验证接收信息
	 * @param parameter
	 *            接收信息
	 * @return
	 */
	public <T> String validate(final T parameter) {
		if (null == parameter) {
			return "请求参数为空";
		}

		List<String> messageList = ViolationUtils.validate(parameter);
		if (CollectionsUtils.isEmpty(messageList)) {
			logger.info("验证接收信息通过！");
			return null;
		}

		String message = CollectionsUtils.convertToString(messageList, ";");
		logger.info("验证接收信息不通过：");
		logger.info(message);
		return message;
	}
	
	/**
     * 修改贷款状态为推送中
     * @Description 
     * @param planId   
     * void  
     * @throws
     * @author zhangmi
     * @date 2015-10-9
     */
    public void updateLoanToWaitSend(String planId){
    	Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("planId", planId);
    	tbjLoanDao.updateStatusToWaitSend(searchParams);
    }
    
    /**
     * 验证是否符合推送要求
     * @Description 
     * @param dataMsg
     * @param planId   
     * void  
     * @throws
     * @author zhangmi
     * @date 2015-10-9
     */
    public boolean checkToWaitSend(DataMsg dataMsg,String planId){
    	Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("planId", planId);
		List<CheckLoanDTO> list = tbjLoanDao.findCheckLoanSend(searchParams);
		if(list!=null&&list.size()>0){
			CheckLoanDTO checkLoanDTO = list.get(0);
			//验证是否是完成状态
			if(!CimsConstant.DEAL_STATUS_FINISH.equals(checkLoanDTO.getDealStatus())){
				dataMsg.setMsg("完成之后才能做推送！");
				dataMsg.setStatus("N");
				return false;
			}
			//验证是否已经正在推送中
			if(checkLoanDTO.getLoanEachStatus().indexOf(CimsConstant.LOAN_EACH_STATUS_TBJ_SENDING)>-1){
				dataMsg.setMsg("正在推送中！");
				dataMsg.setStatus("N");
				return false;
			}
			//验证是否已经推送完成
			if(checkLoanDTO.getLoanEachStatus().indexOf(CimsConstant.LOAN_EACH_STATUS_TBJ_SENDED)>-1){
				dataMsg.setMsg("已经推送完成！");
				dataMsg.setStatus("N");
				return false;
			}
			if(checkLoanDTO.getLoanStatus().indexOf(CimsConstant.LOAN_WAY)>-1){
				dataMsg.setMsg("有在途状态不能进行推送！");
				dataMsg.setStatus("N");
				return false;
			}
			/*if(checkLoanDTO.getLoanStatus().indexOf(CimsConstant.LOAN_FUNDOUT_WIN)>-1){
				dataMsg.setMsg("放款成功的不能进行推送！");
				dataMsg.setStatus("N");
				return false;
			}
			if(checkLoanDTO.getLoanStatus().indexOf(CimsConstant.LOAN_FUNDOUT_WIN)>-1){
				dataMsg.setMsg("放款成功的不能进行推送！");
				dataMsg.setStatus("N");
				return false;
			}
			if(checkLoanDTO.getLoanStatus().indexOf(CimsConstant.LOAN_FUNDOUT_LOSE)>-1){
				dataMsg.setMsg("放款失败的不能进行推送！");
				dataMsg.setStatus("N");
				return false;
			}
			if(checkLoanDTO.getLoanStatus().indexOf(CimsConstant.LOAN_FUNDOUT_LOSE_M)>-1){
				dataMsg.setMsg("拒绝放款不能进行推送！");
				dataMsg.setStatus("N");
				return false;
			}
			if(checkLoanDTO.getLoanStatus().indexOf(CimsConstant.LOAN_FUNDOUT_RJT)>-1){
				dataMsg.setMsg("合同已经废弃不能进行推送！");
				dataMsg.setStatus("N");
				return false;
			}*/
			return true;
		}else{
			dataMsg.setMsg("募集编号为："+planId+",信息不完整！推送失败！");
			dataMsg.setStatus("N");
			return false;
		}
		
    }
}
